"use client"
import { useState, useEffect } from 'react';
import { Space, message, Table, Button, Modal, Tabs, Input, Form, Select, DatePicker, Popconfirm } from 'antd';
import type { TableProps } from 'antd';
import Formlist from './formlist';
import moment from 'moment';
interface DataType {
  id: number;
  name: string;
  age: number;
  address: string;
  Collect: boolean,
  title: string,
  idname: string,
  time: string,
  start: string,
  phone: number,
  day: number,
}
interface SearchFormValues {
  keyword?: string;
  Collect?: boolean | string;
  time?: [moment.Moment, moment.Moment];
}
export default function Home() {
  const { RangePicker } = DatePicker;
  // 控制标头标识
  const [title, setTitle] = useState("添加")
  const [itemobj, setItemobj] = useState({})
  // 控制弹窗的显示
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '客户名称',
      dataIndex: 'address',
      key: 'address',
      render: (address) => {
        return <a href="#">{address}</a>;
      }
    },
    {
      title: '客户状态',
      dataIndex: 'Collect',
      key: 'Collect',
      render: (Collect) => {
        return Collect == true ? '正在跟进' : '未跟进'
      }
    },
    {
      title: '星级客户',
      dataIndex: 'start',
    },
    {
      title: '首联联系人',
      dataIndex: 'title',
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
    },
    {
      title: '创建人员',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '最后跟进',
      dataIndex: 'time',
    },
    {
      title: '未跟进天数',
      dataIndex: 'day',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button variant="link" onClick={() => {
            showModal()
            setTitle("编辑")
            setItemobj(record)
          }}>编辑</Button>
          <Button variant="link">跟进</Button>
          <Button variant="link">置顶</Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            onConfirm={() => {
              let newData = data.filter(item => {
                return item.id != record.id
              })
              console.log(newData, "| newData");
              setFilteredData(newData)
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button variant="link" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState<DataType[]>([
    {
      idname: "SJ20190324010001",
      id: 1,
      name: '订单标题1',
      address: '深圳市伊恩科技有限公司',
      age: 1000000,
      Collect: true,
      title: '赵小刚',
      time: "2019-03-15 17:27",
      start: "★★★★☆",
      phone: 18888888888,
      day: 30,
    },
    {
      idname: "SJ20190324010001",
      id: 2,
      name: '订单标题1',
      address: '深圳市伊恩科技有限公司',
      age: 1000000,
      Collect: false,
      title: '赵小刚',
      time: "2019-03-15 17:27",
      start: "★★★★☆",
      phone: 18888888888,
      day: 30
    },
    {
      idname: "SJ20190324010001",
      id: 3,
      name: '订单标题2',
      address: '深圳市伊恩科技有限公司',
      age: 1000000,
      Collect: true,
      title: '赵小刚',
      time: "2019-03-15 17:27",
      start: "★★★★☆",
      phone: 18888888888,
      day: 30
    },
    {
      idname: "SJ20190324010001",
      id: 4,
      name: '订单标题3',
      address: '深圳市伊恩科技有限公司',
      age: 1000000,
      Collect: true,
      title: '赵小刚',
      time: "2019-03-15 17:27",
      start: "★★★★☆",
      phone: 18888888888,
      day: 30
    },
    {
      idname: "SJ20190324010001",
      id: 5,
      name: '订单标题',
      address: '深圳市伊恩科技有限公司',
      age: 1000000,
      Collect: false,
      title: '赵小刚',
      time: "2019-03-15 17:27",
      start: "★★★★☆",
      phone: 18888888888,
      day: 30
    },
    {
      idname: "SJ20190324010001",
      id: 6,
      name: '订单标题',
      address: '深圳市伊恩科技有限公司',
      age: 1000000,
      Collect: true,
      title: '赵小刚',
      time: "2019-03-15 17:27",
      start: "★★★★☆",
      phone: 18888888888,
      day: 30
    },
    {
      idname: "SJ20190324010001",
      id: 7,
      name: '订单标题',
      address: '深圳市伊恩科技有限公司',
      age: 1000000,
      Collect: false,
      title: '赵小刚',
      time: "2019-03-15 17:27",
      start: "★★★★☆",
      phone: 18888888888,
      day: 30
    },
  ]);

  const onChange = (key: string) => {
    console.log(key);
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '全部客户',
    },
    {
      key: '2',
      label: '我的客户',
    },
    {
      key: '3',
      label: '下属客户',
    },
    {
      key: '4',
      label: '重点客户',
    },
    {
      key: '5',
      label: '我的协作的',
    },
    {
      key: '6',
      label: '下属协作的',
    },
  ];// rowSelection object indicates the need for row selection
  const rowSelection: TableProps<DataType>['rowSelection'] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  const [currentItem, setCurrentItem] = useState<DataType | null>(null);
  const handleFormSuccess = (values: any, isEdit: boolean) => {
    if (isEdit) {
      // 编辑逻辑
      setFilteredData(data.map(item => item.id === values.id ? values : item));
      // setFilteredData(data.map(item => 
      //   item.key === currentItem?.key ? { ...item, ...values, key: currentItem.key } : item
      // ))
      message.success('编辑成功')
    } else {
      // 添加逻辑
      const newItem = {
        id: new Date().getTime(),
        ...values
      };
      setFilteredData([...data, newItem])
      message.success('添加成功')
    }
    setIsModalOpen(false);
    setCurrentItem(null);
  };
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');

  // 搜索
  // 在组件内部添加搜索状态
  const [searchForm] = Form.useForm<SearchFormValues>();
  const [filteredData, setFilteredData] = useState<DataType[]>(data);
  const handleSearch = (values: SearchFormValues) => {
    let result = [...data];

    // 关键词搜索（客户名称、首联联系人、手机号码）
    if (values.keyword) {
      const keyword = values.keyword.toLowerCase();
      result = result.filter(item =>
        item.address.toLowerCase().includes(keyword) ||
        item.title.toLowerCase().includes(keyword) ||
        item.phone.toString().includes(keyword)
      );
    }

    // 客户状态筛选
    if (values.Collect !== undefined) {
      const collectStatus = values.Collect === 'true' ? true : false;
      result = result.filter(item => item.Collect === collectStatus);
    }

    // 时间范围筛选
    if (values.time && values.time.length === 2) {
      const [start, end] = values.time;
      result = result.filter(item => {
        const itemTime = moment(item.time);
        return itemTime.isBetween(start, end, null, '[]'); // [] 表示包含边界
      });
    }

    setFilteredData(result);
    message.success('搜索完成');
  };

  const handleReset = () => {
    searchForm.resetFields();
    setFilteredData(data);
  };

  return (
    <div>
      {/* 顶部导航 */}
      <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
      <Form form={searchForm} onFinish={handleSearch}>
        <Space>
          <Form.Item name="keyword">
            <Input placeholder='搜索关键词' />
          </Form.Item>
          <Form.Item name="Collect">
            <Select placeholder='客户状态' allowClear>
              <Select.Option value="true">正在跟进</Select.Option>
              <Select.Option value="false">未跟进</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="time">
            <RangePicker placeholder={['开始日期', '结束日期']} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">搜索</Button>
            <Button onClick={handleReset}>重置</Button>
          </Form.Item>
        </Space>
      </Form>
      {/* 按钮 */}
      <Space><Button type="primary" onClick={() => {
        showModal()
        setTitle("添加")
        setItemobj({})
      }}>
        +添加
      </Button>
        <Modal footer={null} title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
          <Formlist
            itemobj={itemobj}
            title={title}
            onCancel={handleCancel}
            key={new Date().getTime()}
            onSuccess={handleFormSuccess} />
        </Modal>
        <Button>导入</Button>
        <Button>导出</Button>
        <Button>新建任务</Button>
        <Button>转移客户</Button>
        <Button>移入公海</Button>
        <Button>合并客户</Button>
        <Button>批量编辑</Button>
      </Space>
      <Table<DataType>
        columns={columns}
        dataSource={filteredData}
        rowKey="id"
        rowSelection={{ type: selectionType, ...rowSelection }}
      />
    </div>
  );
}
